import grails.converters.JSON

class DocumentController {
    
    def index = {}

    def updateCurrentDocument = {
     if( params.id != null) {
        def document = Document.get( Long.valueOf(params.id ))
        
        if(document) {
            document.properties = params
            
            if(!document.hasErrors() && document.save()) {
               withFormat {
                    json { render document as JSON }
               }
            }
            else {
                 def message = ['error':"Can't update Document with id ${params.id}"]
                  
                 render message as JSON
            }
        } else {
            def message = ['error':"Can't found Document with id ${params.id}"]
            render message as JSON
        }
      } else {
            def message = ['error':"You must provide Document id"]
            render message as JSON
      }
    }
    
    def createNewDocument = {
          def document = new Document()
          document.documentName = org.apache.commons.lang.RandomStringUtils.random(20, false, true)
          document.documentType = "none"

          System.out.println("document : "+document)
          
          if(!document.hasErrors() && document.save()) {
               withFormat {
                    json { 
                         render document as JSON 
                    }
               }
          }
          else {
               def message = ['error':"Can't create new Document"]
               
               render message as JSON
          }
    }
    
    def getDocumentAsText = {
        if( params.id && Document.exists( params.id ) ) {
            Document doc = Document.get( params.id )
            
            render(contentType:"text/plain", doc.documentContent)
        } 
    }
    
    def getDocumentAsJSON = {
        if( params.id && Document.exists( params.id ) ) {
            withFormat {
               json { render Document.get( params.id ) as JSON }
            }
        }
        
        def error = ['error':"Document not found with id ${params.id}."]
        
        render error as JSON
    }
}
